package com.saifan.wyy_ov.ui.communitylife;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.BBSCommentsBean;
import com.saifan.wyy_ov.data.bean.BBSPostBean;
import com.saifan.wyy_ov.data.bean.PermissionsBean;
import com.saifan.wyy_ov.data.bean.RequestBean;
import com.saifan.wyy_ov.data.bean.SubmitCommentsBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.ui.zoomimage.ZoomImageActivity;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.CircleProgressBottomDialog;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.FileUtils;
import com.saifan.wyy_ov.utils.GsonUtils;
import com.saifan.wyy_ov.utils.ImgUtil;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.PictureUtil;
import com.saifan.wyy_ov.utils.SoftUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.TimeUtils;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0.0
 * @author: Wangli
 * @date: 2015-6-14 15:52:43
 * @descrption 评论列表
 */

public class BBSDetailsActivity extends BaseActivity {
    private android.support.v7.widget.Toolbar toolbar;
    private android.widget.ListView listView;
    private com.saifan.wyy_ov.ui.view.RefreshLayout refreshLayout;
    private IGetData getData;
    private BBSPostBean bbsPostBean;
    private RequestBean requestBean;
    private int page = 0;
    private boolean initFlag;
    private View headerView;
    private CommonAdapter<BBSCommentsBean> adapter;
    private List<BBSCommentsBean> list;
    private ArrayList<String> selectList;
    private final int SELECT_IMG_LOCAL = 1;
    private final int SELECT_IMG_TAKEPHOTO = 2;
    private String picName = "";//图片路径
    private int selectPostion = -1;
    private android.widget.GridView photogrid;
    private BBSPublisAdapter photoAdapter;
    private ImageView statechange;
    private android.widget.EditText comments;
    private boolean inputFlag = true;
    private SubmitCommentsBean submitCommentsBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            bbsPostBean = (BBSPostBean) getIntent().getExtras().getSerializable("data");
        } catch (Exception e){
            LogUtil.d("intent = null");
            ToastUtil.showToast(this, "数据错误");
        }
        setupViews();
        initData();
    }

    private void setupViews() {
        setContentView(R.layout.activity_bbsdetails);
        this.comments = (EditText) findViewById(R.id.comments);
        this.statechange = (ImageView) findViewById(R.id.state_change);
        this.photogrid = (GridView) findViewById(R.id.photo_grid);
        this.refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        this.listView = (ListView) findViewById(R.id.listView);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(bbsPostBean.getFTB_BT());
        headerView = getLayoutInflater().inflate(R.layout.bbsdetails_header, null);
        selectList = new ArrayList<String>();
        photoAdapter = new BBSPublisAdapter(selectList, BBSDetailsActivity.this);
        photogrid.setAdapter(photoAdapter);
        photogrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (selectList.size() < 4) {
                    selectPostion = position - 1;
                    if (position == 0) {
                        showSelectImgDialog(false);
                    } else {
                        showSelectImgDialog(true);
                    }
                } else {
                    selectPostion = position;
                    showSelectImgDialog(true);
                }

            }
        });

        comments.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    photogrid.setVisibility(View.GONE);
                    statechange.setImageResource(R.drawable.shape213);
                    inputFlag = true;
                }
            }
        });
        statechange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputFlag) {
                    photogrid.setVisibility(View.VISIBLE);
                    statechange.setImageResource(R.drawable.photocamera_small);
                    SoftUtil.hideSoftInput(BBSDetailsActivity.this, comments);
                    comments.clearFocus();
                    inputFlag = false;
                } else {
                    photogrid.setVisibility(View.GONE);
                    statechange.setImageResource(R.drawable.shape213);
                    comments.requestFocus();
                    SoftUtil.showSoftInput(BBSDetailsActivity.this, comments, 200);
                    inputFlag = true;
                }
            }
        });
        ImgUtil.DisPlayImg(bbsPostBean.getWYKHDA_TXLJ(), ((ImageView) headerView.findViewById(R.id.header)), BBSDetailsActivity.this);
        ((TextView)headerView.findViewById(R.id.nick_name)).setText(StringUtil.returnShow(bbsPostBean.getWYKHDA_LC()));
        ((TextView)headerView.findViewById(R.id.content)).setText(StringUtil.returnShow(bbsPostBean.getFTB_LR()));
        ((TextView)headerView.findViewById(R.id.time)).setText(TimeUtils.getTime(bbsPostBean.getFTB_FTSJ()));
        final String[] imgsPath = bbsPostBean.getFTB_TPLJ().split(",");
        if (!StringUtil.isNullOrEmpty(bbsPostBean.getFTB_TPLJ()) && imgsPath != null && imgsPath.length > 0){
            for (int i = 0; i < 4; i++){
                int id = getResources().getIdentifier("img" + i, "id", BBSDetailsActivity.this.getPackageName());
                if (i < imgsPath.length){
                    headerView.findViewById(id).setVisibility(View.VISIBLE);
                    ImgUtil.DisPlayImg(imgsPath[i], ((ImageView) headerView.findViewById(id)), BBSDetailsActivity.this);
                    final int finalI = i;
                    headerView.findViewById(id).setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                           Intent intent = new Intent(BBSDetailsActivity.this, ZoomImageActivity.class);
                           ArrayList<String> imgs = new ArrayList<String>();
                           for (int m = 0; m < imgsPath.length; m++) {
                               imgs.add(imgsPath[m]);
                           }
                           intent.putStringArrayListExtra("img", imgs);
                           intent.putExtra("position", finalI);
                           startActivity(intent);
                       }
                   });
                } else {
                    headerView.findViewById(id).setVisibility(View.INVISIBLE);
                }
            }
        } else {
            headerView.findViewById(R.id.imgs).setVisibility(View.GONE);
        }
        listView.addHeaderView(headerView);
        list = new ArrayList<BBSCommentsBean>();
        adapter = new CommonAdapter<BBSCommentsBean>(BBSDetailsActivity.this, list, R.layout.bbsdetails_item) {
            @Override
            public void convert(ViewHolderHelper helper, BBSCommentsBean item) {
                helper.setText(R.id.nick_name, StringUtil.isNullOrEmpty(item.getWYKHDA_LC()) ? "匿名" : item.getWYKHDA_LC());
                helper.setText(R.id.time, TimeUtils.getTimeSeconds(item.getGTB_FBSJ()));
                helper.setText(R.id.content, StringUtil.returnShow(item.getGTB_LR()));
                helper.setImageByUrl(R.id.header, item.getWYKHDA_TXLJ());
                LinearLayout imgs = helper.getView(R.id.imgs);
                imgs.setVisibility(StringUtil.isNullOrEmpty(item.getGTP_TPLJ()) ? View.GONE : View.VISIBLE);
                if (!StringUtil.isNullOrEmpty(item.getGTP_TPLJ())){
                    final String[] imgsPath = item.getGTP_TPLJ().split(",");
                    for (int i = 0; i < 4; i++){
                        int id = getResources().getIdentifier("img" + i, "id", BBSDetailsActivity.this.getPackageName());
                        if (i < imgsPath.length){
                            helper.getView(id).setVisibility(View.VISIBLE);
                            helper.setImageByUrl(id, imgsPath[i]);
                            final int finalI = i;
                            helper.getView(id).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(BBSDetailsActivity.this, ZoomImageActivity.class);
                                    ArrayList<String> imgs = new ArrayList<String>();
                                    for (int m = 0; m < imgsPath.length; m++) {
                                        imgs.add(imgsPath[m]);
                                    }
                                    intent.putStringArrayListExtra("img", imgs);
                                    intent.putExtra("position", finalI);
                                    startActivity(intent);
                                }
                            });
                        } else {
                            helper.getView(id).setVisibility(View.INVISIBLE);
                        }
                    }
                }
            }
        };
        listView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                refreshLayout.setRefreshing(true);
                initData();
            }
        });
        refreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                CircleProgressBottomDialog.showDialog(BBSDetailsActivity.this);
                if (page > 0)
                    refreshLayout.setLoading(true);
                page++;
                initData();
            }
        });
    }

    private void initData(){
        if (getData == null)
            getData = new GetData();
        if (requestBean == null){
            requestBean = new RequestBean();
            requestBean.setGTB_FTBWJ(bbsPostBean.getFTB_ZJ());
        }
        requestBean.setPage(page);
        String tip;
        if (initFlag)
            tip = "";
        else
            tip = "正在加载...";
        getData.getDataJson(BBSDetailsActivity.this, Api.BBS.COMMENTSLIST, requestBean, tip, new ResponseData() {
            @Override
            public void onSuccess(String json) {
                if (StringUtil.isNullOrEmpty(json)){
                    if (page == 0){
                        handler.sendEmptyMessage(0);//没有数据
                    } else {
                        page -- ;
                        handler.sendEmptyMessage(1);//没有更多数据
                    }
                } else {
                    Message message = handler.obtainMessage();
                    List<BBSCommentsBean> tempList = (new Gson()).fromJson(json, new TypeToken<List<BBSCommentsBean>>() { }.getType());
                    if (page == 0){//下拉刷新
                        if (tempList != null && tempList.size() > 0){
                            message.what = 2;
                            message.obj = tempList;
                        } else {
                            message.what = 0;
                        }
                    } else {//加载更多
                        if (tempList != null && tempList.size() > 0){
                            message.what = 3;
                            message.obj = tempList;
                        } else {
                            message.what = 1;
                            page--;
                        }
                    }
                    handler.sendMessage(message);
                    CircleProgressBottomDialog.closeDialog();
                }
                initFlag = true;
            }

            @Override
            public void onFailed(String str) {
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                CircleProgressBottomDialog.closeDialog();
                if (page >= 0) {
                    page --;
                }
            }
        });
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:

                    ToastUtil.showToast(BBSDetailsActivity.this, "暂无评论");
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 1:
//                    ToastUtil.showToast(BBSDetailsActivity.this, "暂无更多评论");
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 2:

                    list = (List<BBSCommentsBean>) msg.obj;
                    adapter.mDatas = list;
                    adapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 3:
                    list.addAll((List<BBSCommentsBean>) msg.obj);
                    adapter.mDatas = list;
                    adapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                default:
                    break;
            }
        }
    };

    //显示选择图片的对话框
    private void showSelectImgDialog(boolean hasDelete) {
        String[] items;
        if (hasDelete)
            items = new String[]{"从相册中选择", "拍照", "删除"};
        else
            items = new String[]{"从相册中选择", "拍照"};
        AlertDialog dialog = new AlertDialog.Builder(BBSDetailsActivity.this)
                .setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            selectImg();
                        } else if (which == 2) {
                            selectList.remove(selectPostion);
                            photoAdapter.list = selectList;
                            photoAdapter.notifyDataSetChanged();
                        } else {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, SELECT_IMG_TAKEPHOTO);
                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }

    //从相册中选择图片
    private void selectImg() {
        Intent intent = new Intent(BBSDetailsActivity.this, PhotoAlbumActivity.class);
        intent.putStringArrayListExtra("data", selectList);
        intent.putExtra("count", 4);
        startActivityForResult(intent, SELECT_IMG_LOCAL);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_IMG_LOCAL) {
                this.selectList = data.getStringArrayListExtra("data");
                photoAdapter.list = selectList;
                photoAdapter.notifyDataSetChanged();
            } else if (requestCode == SELECT_IMG_TAKEPHOTO) {
                Bitmap bitmap = data.getParcelableExtra("data") ;
                File file = FileUtils. bitmapToFile(bitmap);
                FileUtils.toAlbum(this,file);
                picName=file.getAbsolutePath();
                if (selectPostion == -1) {
                    this.selectList.add(picName);
                } else {
                    this.selectList.set(selectPostion, picName);
                }
                photoAdapter.list = selectList;
                photoAdapter.notifyDataSetChanged();
            }
        }
    }

    public void submit(View view){
        if (getRoomInfoBean().getUserType() == 2){
            for (PermissionsBean permissionsBean : getPermissions()){
                if (permissionsBean.getYKQX_GNMC().equals("业主论坛")){
                    if (selectList.size() < 1 && StringUtil.isNullOrEmpty(comments.getText().toString().trim())){
                        ToastUtil.showToast(BBSDetailsActivity.this, "没有内容需要发送");
                        return;
                    }
                    if (submitCommentsBean == null){
                        submitCommentsBean = new SubmitCommentsBean();
                        submitCommentsBean.setGTB_FTBWJ(bbsPostBean.getFTB_ZJ());
                        submitCommentsBean.setXMBS(getRoomInfoBean().getXMBS());
                        submitCommentsBean.setGTB_KHWJ(getRoomInfoBean().getWYKHDA_ZJ());
                    }
                    submitCommentsBean.setGTB_LR(comments.getText().toString());
                    RequestParams params = new RequestParams();
                    params.addBodyParameter("Comments", GsonUtils.toJson(submitCommentsBean));
                    for (int i = 0; i < selectList.size(); i++) {
                        File file = new File(PictureUtil.getCompressBitmap(selectList.get(i)));
                        if (file.exists()) {
                            params.addBodyParameter(file.getName(), file);
                        }
                    }
                    getData.getDataJson(BBSDetailsActivity.this, Api.BBS.COMMENTSSUBMIT, params, "正在请求...", new ResponseData() {
                        @Override
                        public void onSuccess(String json) {
                            ToastUtil.showToast(BBSDetailsActivity.this, "提交成功");
                            comments.setText("");
                            selectList.clear();
                            photoAdapter.notifyDataSetChanged();
                            photogrid.setVisibility(View.GONE);
                            statechange.setImageResource(R.drawable.shape213);
                            SoftUtil.hideSoftInput(BBSDetailsActivity.this, comments);
                            comments.clearFocus();
                            inputFlag = true;
                        }

                        @Override
                        public void onFailed(String str) {

                        }
                    });
                    return;
                }
            }
            ToastUtil.showToast(BBSDetailsActivity.this, "您的权限不能进行此操作");
            return;
        } else if (getRoomInfoBean().getUserType() == 3){
            ToastUtil.showToast(BBSDetailsActivity.this, "您的权限不能进行此操作");
            return;
        }

        if (selectList.size() < 1 && StringUtil.isNullOrEmpty(comments.getText().toString().trim())){
            ToastUtil.showToast(BBSDetailsActivity.this, "没有内容需要发送");
            return;
        }
        if (submitCommentsBean == null){
            submitCommentsBean = new SubmitCommentsBean();
            submitCommentsBean.setGTB_FTBWJ(bbsPostBean.getFTB_ZJ());
            submitCommentsBean.setXMBS(getRoomInfoBean().getXMBS());
            submitCommentsBean.setGTB_KHWJ(getRoomInfoBean().getWYKHDA_ZJ());
        }
        submitCommentsBean.setGTB_LR(comments.getText().toString());
        RequestParams params = new RequestParams();
        params.addBodyParameter("Comments", GsonUtils.toJson(submitCommentsBean));
        for (int i = 0; i < selectList.size(); i++) {
            File file = new File(PictureUtil.getCompressBitmap(selectList.get(i)));
            if (file.exists()) {
                params.addBodyParameter(file.getName(), file);
            }
        }
        getData.getDataJson(BBSDetailsActivity.this, Api.BBS.COMMENTSSUBMIT, params, "正在请求...", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                ToastUtil.showToast(BBSDetailsActivity.this, "提交成功");
                comments.setText("");
                selectList.clear();
                photoAdapter.notifyDataSetChanged();
                photogrid.setVisibility(View.GONE);
                statechange.setImageResource(R.drawable.shape213);
                SoftUtil.hideSoftInput(BBSDetailsActivity.this, comments);
                comments.clearFocus();
                inputFlag = true;
            }

            @Override
            public void onFailed(String str) {

            }
        });
    }

}
